package com.simple.business.service.utilService;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.simple.business.domain.entity.config.Dictionary;
import com.simple.business.mapper.utilMapper.DictionaryMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class DictionaryService {
    @Resource
    private DictionaryMapper dictionaryMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    private QueryWrapper<Dictionary> getDictionaryQueryWrapper(String mapGroup, String mapKey) {
        QueryWrapper<Dictionary> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("map_key", mapKey);
        queryWrapper.eq("map_group", mapGroup);
        return queryWrapper;
    }


    public String getDictionaryValue(String mapGroup,String mapKey) {
        String key = mapGroup+"::"+mapKey;
        Object cacheStr = redisTemplate.opsForValue().get(key);
        if (cacheStr != null) {
            return cacheStr.toString();
        }

        Dictionary dictionary = dictionaryMapper.selectOne(getDictionaryQueryWrapper(mapGroup,mapKey));
        if (dictionary != null && StringUtils.isNotBlank(dictionary.getMapValue())) {
            redisTemplate.opsForValue().set(key, dictionary.getMapValue());
            return dictionary.getMapValue();
        }
        return null;
    }

    @Transactional
    public boolean updateDictionaryValue(String mapGroup,String mapKey, String mapValue) {
        String key = mapGroup+"::"+mapKey;
        Dictionary dictionary = dictionaryMapper.selectOne(getDictionaryQueryWrapper(mapGroup,mapKey));
        boolean isSuccess;
        if (dictionary == null) {
            dictionary = new Dictionary();
            dictionary.setMapGroup(mapGroup);
            dictionary.setMapKey(mapKey);
            dictionary.setMapValue(mapValue);
            isSuccess = dictionaryMapper.insert(dictionary) > 0;
        } else {
            redisTemplate.delete(key);
            dictionary.setMapValue(mapValue);
            isSuccess = dictionaryMapper.updateById(dictionary) > 0;
        }
        return isSuccess;
    }
}
